%% Author: casey
%% Created: Mar 7, 2007
%% Description: TODO: Add desciption to new_file
-module(dc_com).
-behaviour(gen_event).

-include("dc_types.hrl").

%%
%% Include files
%%

%%
%% Exported Functions
%%

-export([test/2]).
-export([run/1]).
-export([init_client/1, client_loop/1]).

%%
%% API Functions
%%

test(Host, Port) ->
%%    run(#conn_info{host="sheffmainuk.no-ip.org", 
    run(#conn_info{host=Host, 
                   port=Port, 
                   nick="erlDC", 
                   password=nil}).

run(ConnInfo) ->
    Handle = init_client(ConnInfo),
    client_loop(Handle).

init_client(ConnInfo) ->
    Handle = client_connect(ConnInfo),
    gen_event:start({local, dc_client_man}),
    gen_event:add_handler(dc_client_man, dc_auth, Handle),
	Handle.

client_loop(Handle) ->
    SendCmd = fun (Cmd) -> gen_event:notify(dc_client_man, Cmd) end,
    lists:map(SendCmd, wait_resp()),
	client_loop(Handle).

%%
%% Local Functions
%%

client_connect(ConnInfo=#conn_info{host=Host,port=Port}) ->
    case gen_tcp:connect(Host, Port, [list]) of
        {ok, Socket} ->
            #handle{socket=Socket,conn_info=ConnInfo}
	end.

resp_to_cmd(S) ->
    case regexp:first_match(S, "[$][^ \t]+") of
	    {match, _, CmdLen} ->
            Cmd = string:sub_string(S, 1, CmdLen),
            Args = string:sub_string(S, CmdLen+2),
            case Cmd of
                "$Lock" ->
                    [Key, Pk] = string:tokens(Args, " "),
                    {lock, Key, Pk};
                "$ValidateDenide" ->
                    validate_denied;
                "$GetPass" ->
                    get_pass;
                "$LogedIn" ->
                    logged_in;
                "$BadPass" ->
                    bad_pass;
                "$HubName" ->
                    {hub_name, Args};
                "$NickList" ->
                    {nick_list, string:tokens(Args, "$")};
                "$OpList" ->
                    {op_list, string:tokens(Args, "$")};
                "$ForceMove" ->
                    {force_move, Args};
                "$Hello" ->
                    hello;
%%                "$To" ->
%%                    {to, Args};
                _ ->
                    {unsupported, Cmd, Args}
            end;
        nomatch ->
            {message, S}
    end.
    
%%handle_cmd(Cmd) ->
%%    io:fwrite("~p~n", [Cmd]).

wait_resp() ->
    receive
        {tcp, _Socket, Data} ->
            lists:map(fun resp_to_cmd/1, string:tokens(Data, "|"))
    end.

